package com.atao.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证身份唯一
 */
public class CurAuthentication {

    public static String getUserInfo(HttpServletRequest request) {
        String ipAddress = getIpAddress(request);
        Map<String, String> osAndBrowserInfo = getOsAndBrowserInfo(request);
        String userInfo = String.join(" ", osAndBrowserInfo.values());
        userInfo += ipAddress;
        return userInfo;
    }


    /**
     * 获取ip
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;

        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");
        System.out.println("====ipAddresses:"+ipAddresses);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            //打印所有头信息
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            System.out.println(s+"::::"+header);
        }
        System.out.println("headerNames:"+ headerNames.toString());
        System.out.println("RemoteHost:"+request.getRemoteHost());
        System.out.println("RemoteAddr:"+request.getRemoteAddr());

        String unknown = "unknown";
        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取操作系统,浏览器及浏览器版本信息
     */
    public static Map<String, String> getOsAndBrowserInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        String browserDetails = request.getHeader("User-Agent" );
        String user = browserDetails.toLowerCase();

        String os = "";
        String browser = "";
        //=================OS Info=======================
        if (browserDetails.toLowerCase().contains("windows" )) {
            os = "Windows";
        } else if (browserDetails.toLowerCase().contains("mac" )) {
            os = "Mac";
        } else if (browserDetails.toLowerCase().contains("x11" )) {
            os = "Unix";
        } else if (browserDetails.toLowerCase().contains("android" )) {
            os = "Android";
        } else if (browserDetails.toLowerCase().contains("iphone" )) {
            os = "IPhone";
        } else {
            os = "UnKnown, More-Info: " + browserDetails;
        }
        //===============Browser===========================
        if (user.contains("edge" )) {
            browser = (browserDetails.substring(browserDetails.indexOf("Edge" )).split(" " )[0]).replace("/" , "-" );
        } else if (user.contains("msie" )) {
            String substring = browserDetails.substring(browserDetails.indexOf("MSIE" )).split(";" )[0];
            browser = substring.split(" " )[0].replace("MSIE" , "IE" ) + "-" + substring.split(" " )[1];
        } else if (user.contains("safari" ) && user.contains("version" )) {
            browser = (browserDetails.substring(browserDetails.indexOf("Safari" )).split(" " )[0]).split("/" )[0]
                    + "-" + (browserDetails.substring(browserDetails.indexOf("Version" )).split(" " )[0]).split("/" )[1];
        } else if (user.contains("opr" ) || user.contains("opera" )) {
            if (user.contains("opera" )) {
                browser = (browserDetails.substring(browserDetails.indexOf("Opera" )).split(" " )[0]).split("/" )[0]
                        + "-" + (browserDetails.substring(browserDetails.indexOf("Version" )).split(" " )[0]).split("/" )[1];
            } else if (user.contains("opr" )) {
                browser = ((browserDetails.substring(browserDetails.indexOf("OPR" )).split(" " )[0]).replace("/" , "-" ))
                        .replace("OPR" , "Opera" );
            }
        } else if (user.contains("chrome" )) {
            browser = (browserDetails.substring(browserDetails.indexOf("Chrome" )).split(" " )[0]).replace("/" , "-" );
        } else if ((user.contains("mozilla/7.0" )) || (user.contains("netscape6" )) ||
                (user.contains("mozilla/4.7" )) || (user.contains("mozilla/4.78" )) ||
                (user.contains("mozilla/4.08" )) || (user.contains("mozilla/3" ))) {
            browser = "Netscape-?";
        } else if (user.contains("firefox" )) {
            browser = (browserDetails.substring(browserDetails.indexOf("Firefox" )).split(" " )[0]).replace("/" , "-" );
        } else if (user.contains("rv" )) {
            String IEVersion = (browserDetails.substring(browserDetails.indexOf("rv" )).split(" " )[0]).replace("rv:" , "-" );
            browser = "IE" + IEVersion.substring(0, IEVersion.length() - 1);
        } else {
            browser = "UnKnown, More-Info: " + browserDetails;
        }
        map.put("os" , os);
        map.put("browser" , browser);
        return map;
    }
}
